package com.meritdata.cloud.data.service.application.service.impl;


import com.meritdata.cloud.data.base.Page;
import com.meritdata.cloud.data.service.application.dao.IAppBindApiDao;
import com.meritdata.cloud.data.service.application.dao.IApplicationDao;
import com.meritdata.cloud.data.service.application.model.DataApiAppAuth;
import com.meritdata.cloud.data.service.application.service.IAppBindApiService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class AppBindApiService implements IAppBindApiService {
    @Autowired
    private IAppBindApiDao dao;

    @Override
    public Page page(Page<DataApiAppAuth> page) {
        return dao.pageHql("from DataApiAppAuth", page.getPageNum(), page.getPageSize(), null);
    }

    @Override
    public boolean save(DataApiAppAuth apiAppAuth) {
        dao.save(apiAppAuth);
        return true;
    }

    @Override
    public List<Map<String, Object>> getByAppId(Long id) {
        String sql = "select auth.id as sid, api.*, cate.name as categroy from TD_DATA_API_APP_AUTH auth join TD_DATA_API api on auth.API_ID = api.ID and auth.APP_ID = ? left join TD_DATA_API_CATEGORY cate on cate.ID = api.CATEGORY_ID";
        return dao.findSql(sql, id);
    }

    @Override
    public boolean bindService(Long appId, String services) {
        dao.deleteEqualField("appId", appId);
        if(StringUtils.isNotBlank(services)){
            String[] apis = services.split("_");
            for (int i = 0; i < apis.length; i++) {
                String apiId = apis[i];
                DataApiAppAuth apiAppAuth = new DataApiAppAuth();
                apiAppAuth.setApiId(Long.valueOf(apiId));
                apiAppAuth.setAppId(appId);
                dao.save(apiAppAuth);
            }
        }
        return true;
    }

    @Override
    public boolean delete(Long sid) {
        return dao.delete(sid) > 0;
    }

    @Override
    public boolean delete(String services) {
        if(StringUtils.isNotBlank(services)){
            String[] apis = services.split("_");
            for (int i = 0; i < apis.length; i++) {
                String id = apis[i];
                dao.delete(Long.valueOf(id));
            }
        }
        return true;
    }
}
